package com.hu.ta.assignment6.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

import javax.mail.Header;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

import com.hu.ta.assignment6.beans.EmailClass;
import com.hu.ta.assignment6.beans.EmailContent;

public class FileEmail extends FileIO {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6047596026214995109L;
	protected EmailContent content;
	protected EmailClass classification;

	public FileEmail(String path) {
		super(path);
	}

	private String readFileAsString(File filePath) throws IOException {
		StringBuffer fileData = new StringBuffer();
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
		}
		reader.close();
		if (fileData.length() == 0) {
			System.out.println("File is 0 bytes long!");
		}
		return fileData.toString();
	}

	@Override
	public boolean read() {
		try {
			content = new EmailContent();
			FileInputStream fis = new FileInputStream(this);
			// // Erste Zeile ignorieren
			// while (fis.read() != EOL) {
			// }
			Session s = Session.getDefaultInstance(new Properties());
			MimeMessage message = new MimeMessage(s, fis);

			message.getAllHeaderLines();
			for (@SuppressWarnings("unchecked")
			Enumeration<Header> e = message.getAllHeaders(); e
					.hasMoreElements();) {
				Header h = e.nextElement();
				// System.out.println(h.getName() + "=" + h.getValue());
				content.addHeader(h);
			}

			content.addSubject(message.getSubject());
			content.addContent(message.getContent());

			return true;
		} /*
		 * catch (FileNotFoundException e1) { e1.printStackTrace(); } catch
		 * (MessagingException e1) { // TODO Auto-generated catch block
		 * e1.printStackTrace(); } catch (IOException e1) { // TODO
		 * Auto-generated catch block e1.printStackTrace();
		 * 
		 * }
		 */
		catch (Exception e) {
			try {
				content.addSubject(readFileAsString(this));
			} catch (IOException e2) {
				e2.printStackTrace();
			}
		}

		return false;
	}

	@Override
	public boolean write() {
		// TODO Auto-generated method stub
		return false;
	}

	public EmailContent getContent() {
		return content;
	}

	public EmailClass getClassification() {
		return classification;
	}

	public void setClassification(EmailClass classification) {
		this.classification = classification;
	}

}
